<!--日期选择M-->

<template>
  <div class="w-h-full" :style="{
    textAlign: 'center',
    lineHeight: $parent.$parent.layoutItem.layoutItemConfigData.height - 2 + 'px'
  }">
    <!--组件遮罩层，用于在设计器中显示-->
    <div v-if="shade" class="shade"></div>

    <Input ref="Input" v-model="inputValue"
           :type="'text'"
           :size="component.compConfigData.inputConfig.size"
           :placeholder="component.compConfigData.inputConfig.placeholder"
           :clearable="component.compConfigData.inputConfig.clearable"
           :disabled="component.compConfigData.inputConfig.disabled"
           :readonly="component.compConfigData.inputConfig.readonly"
           :icon="'ios-calendar-outline'"
           :style="Object.assign({
            width: component.compConfigData.inputConfig.inputStyle.width,
            transform: 'scale('+component.compConfigData.inputConfig.inputStyle.scaleValue+')'
           }, inputStyleObject)"
           @on-focus="inputOnFocusHandler"
           @on-click="inputOnFocusHandler"
    />

    <van-calendar ref="Calendar"
                  v-model="visible"
                  :type="component.compConfigData.type"
                  :title="component.compConfigData.title"
                  :color="component.compConfigData.color"
                  :row-height="component.compConfigData.rowHeight"
                  :show-mark="component.compConfigData.showMark"
                  :show-title="component.compConfigData.showTitle"
                  :show-subtitle="component.compConfigData.showSubtitle"
                  :show-confirm="component.compConfigData.showConfirm"
                  :confirm-text="component.compConfigData.confirmText"
                  :confirm-disabled-text="component.compConfigData.confirmDisabledText"

                  :position="component.compConfigData.position"
                  :round="component.compConfigData.round"
                  :closeOnClickOverlay="component.compConfigData.closeOnClickOverlay"
                  :safeAreaInsetBottom="component.compConfigData.safeAreaInsetBottom"
                  :get-container="component.compConfigData.getContainer"

                  :max-range="component.compConfigData.maxRange"
                  :range-prompt="component.compConfigData.rangePrompt"
                  @open="onOpenHandler"
                  @confirm="confirmHandler"/>
  </div>
</template>

<script>

import FuncCompMixin from '@/mixin/FuncCompMixin'
import PnDesigner from '@/utils/PnDesigner'

import Calendar from 'vant/lib/calendar';
import 'vant/lib/calendar/style';

const _this = {
  name: 'VanCalendarComp', // 此名称必须填写，且必须与组件文件名相同
  mixins: [FuncCompMixin],
  components: {
    [Calendar.name]: Calendar
  },
  attr: {
    version: '1.0',
    configDataTemp: Object.assign({

      inputConfig: {
        size: 'large',
        placeholder: '请选择',
        clearable: false,
        disabled: false,
        readonly: true,
        inputStyle: {
          scaleValue: 1,
          width: '150px',
          backgroundColor: '#263238',
          color: '#fff',
          borderColor: '#2196f3'
        }
      },

      type: 'single',
      title: '选择日期',
      color: '#2196f3',
      rowHeight: 60, // 日期行高
      showMark: true, // 是否显示月份背景水印
      showTitle: true, // 是否展示日历标题
      showSubtitle: true, // 是否展示日历副标题（年月）
      showConfirm: true, // 是否展示确认按钮
      confirmText: '确定', // 确认按钮的文字
      confirmDisabledText: '确定', // 确认按钮处于禁用状态时的文字

      // poppable 为 true 时
      position: 'bottom', // 弹出位置，可选值为 top right left
      round: true, // 是否显示圆角弹窗
      closeOnClickOverlay: true, // 是否在点击遮罩层后关闭
      safeAreaInsetBottom: true, // 是否开启底部安全区适配
      getContainer: '#app',

      // Calendar 的 type 为 multiple 时
      maxRange: 10, // 日期区间最多可选天数
      rangePrompt: '选择天数不能超过 10 天',

      // formatting: 'yyyy-MM-dd',

      onConfirmCode: ''

    }, PnDesigner.buildFuncCompGlobalField(), PnDesigner.buildFuncCompInteractionConfiguration([
      PnDesigner.buildFuncCompInteractionStreamItem('itemConfirm', [
        PnDesigner.buildFuncCompInteractionFieldsMapItem('value','')
      ])
    ]))
  },
  data() {
    return {
      visible: false,
      inputValue: '',
      value: ''
    }
  },
  destroyed() {
    this.$EventBus.$off('pn_show_van_calendar_m_'+this.component.id)
  },
  mounted() {
    this.init();

    if (!this.$store.state.release.pageMetadata) {
      this.$EventBus.$off('pn_show_van_calendar_m_'+this.component.id)
      this.$EventBus.$on('pn_show_van_calendar_m_'+this.component.id, () => {
        this.visible = !this.visible
      })
    }
  },
  methods: {
    init() { // 组价初始化函数，函数名必须使用init，不可更改
      this.initDatasource(() => {
        this.runCustomGlobalJsCode()
      }, (result) => {
        this.runCustomGlobalJsCode()
      });
    },

    inputOnFocusHandler () {
      this.visible = true
    },

    onOpenHandler() {
      if (this.inputValue) {
        if (this.component.compConfigData.type == 'single') {
          let strDate = this.inputValue.replace(/-/g,"/")
          this.Calendar.reset(new Date(strDate))
        }else {
          let resetArr = []
          let strDateArr = this.inputValue.split(',')
          strDateArr.forEach(item => {
            resetArr.push(new Date(item.replace(/-/g,"/")))
          })
          this.Calendar.reset(resetArr)
        }
      }else {
        this.Calendar.reset()
      }
    },

    confirmHandler(selectedData) {
      this.value = selectedData
      let formatDate = ''
      if (this.component.compConfigData.type == 'single') {
        formatDate = this.$PnUtil.dateFormatter(selectedData, 'yyyy-MM-dd')
      }else{
        let arr = []
        selectedData.forEach(item => {
          arr.push(this.$PnUtil.dateFormatter(item, 'yyyy-MM-dd'))
        })
        formatDate = arr.toString()
      }
      this.inputValue = formatDate
      this.$PnDesigner.launchInteractionStream(this.component.compConfigData, 'itemConfirm', {value: formatDate})
      try {
        let value = formatDate
        eval(this.component.compConfigData.onConfirmCode)
      }catch (e) {
        console.error(e)
      }
      this.visible = false
    }
  },
  computed: {

    inputStyleObject () {
      return {
        '--background-color': this.component.compConfigData.inputConfig.inputStyle.backgroundColor,
        '--color': this.component.compConfigData.inputConfig.inputStyle.color,
        '--border-color': this.component.compConfigData.inputConfig.inputStyle.borderColor,
      }
    },

    Calendar () {
      return this.$refs.Calendar
    }
  }
};

export default _this
</script>

<style scoped>
div {
  color: #323233 !important;
}

>>> .ivu-input {
  background-color: var(--background-color);
  border: 1px solid var(--border-color);
  color: var(--color);
}
>>> .ivu-input::-webkit-input-placeholder{
  color: var(--color);
}
>>> .ivu-input::-moz-placeholder{
  color: var(--color);
}
>>> .ivu-input-icon {
  color: var(--color);
  font-size: 18px !important;
}
</style>
